package com.hand.wfive.fragment.sign

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import cn.hzw.doodle.DoodlePen
import cn.hzw.doodle.IDoodleListener
import cn.hzw.doodle.core.IDoodle
import cn.hzw.doodle.core.IDoodleSelectableItem
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.ad.AdFragment
import com.hand.wfive.base.BaseFragment
import com.hand.wfive.entity.Params
import com.hand.wfive.util.ActivityManagerUtil
import com.hand.wfive.util.FuncSwitchUtils
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.view.CustomDoodleView
import com.hand.wfive.view.SizeTransformation
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import kotlinx.android.synthetic.main.fragment_sign_item.fl_sign
import org.jetbrains.anko.support.v4.runOnUiThread
import org.jetbrains.anko.support.v4.toast
import top.zibin.luban.CompressionPredicate
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import kotlin.concurrent.thread

class SignItemFragment : AdFragment() {

    companion object {
        fun load(url: String, listener: Listener): BaseFragment {
            val fragment = SignItemFragment()
            fragment.arguments = Bundle()
            fragment.arguments?.putString(Params.url, url)
            fragment.setListener(listener)
            return fragment
        }
    }

    private lateinit var mImageUrl: String

    private var mDoodleView: CustomDoodleView? = null
    private val mSignData = ArrayList<IDoodleSelectableItem?>()

    private var mListener: Listener? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mImageUrl = arguments?.getString(Params.url) ?: ""
    }

    override fun getLayoutId() = R.layout.fragment_sign_item

    override fun initKotlinWidget() {

        showLoading("正在加载")
        if (mImageUrl.startsWith("http")){
            // 加载图片
            Glide.with(this).asBitmap().load(mImageUrl)
                .transform(SizeTransformation(resources.displayMetrics.densityDpi / 72 * 1000L))
                .into(object : CustomTarget<Bitmap>() {
                    override fun onLoadCleared(placeholder: Drawable?) = Unit
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {

                        mImageUrl =  ImageUtils.saveBitmapJPG(
                            mContext, resource, App.getContext().cacheTempPath
                        )
                        Log.e("onResourceReady",mImageUrl)
                        loadImageData()
//                        initDoodleView(resource)
                    }
                })
        }else{
            loadImageData()
        }
        // 加载图片
       /* Glide.with(this).asBitmap().load(mImageUrl)
            .transform(SizeTransformation(resources.displayMetrics.densityDpi / 72 * 1000L))
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadCleared(placeholder: Drawable?) = Unit
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    initDoodleView(resource)
                }
            })*/
    }

    private fun loadImageData(){
        val file = File(mImageUrl)
        val fileLength = file.length()
        Log.d("testXX", "---------SignItemFragment local fileLength:$fileLength    filePath:${mImageUrl}")
        if (fileLength >= ActivityManagerUtil.getMemorySize()) {
            doCompress(mImageUrl)
        }else{
            initDoodleView(ImageUtils.getBitmapFromFile(file))
            hideLoading()
        }
    }

    private fun initDoodleView(resource: Bitmap) {
        mDoodleView = CustomDoodleView(mContext, resource, object : IDoodleListener {
            override fun onSaved(doodle: IDoodle, doodleBitmap: Bitmap, callback: Runnable) {
                println("onSaved")
                thread {
                    val savePath = ImageUtils.saveBitmapJPG(
                        mContext, doodleBitmap, App.getContext().cacheTempPath
                    )
                    runOnUiThread {
                        callback.run()
                        mListener?.onItemSave(Pair(true, savePath))
                    }
                }
            }

            override fun onReady(doodle: IDoodle) {
                mDoodleView?.pen = DoodlePen.BITMAP
                mDoodleView?.isEditMode = true
            }
        })
        fl_sign.addView(mDoodleView)
    }


    private fun doCompress(path: String) {
        Luban.with(mContext)
            .load(path)
            .ignoreBy(100)
            .setTargetDir(App.getContext().cacheTempPath)
            .filter(CompressionPredicate { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) })
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {

                }

                override fun onSuccess(file: File) {
                    val fileLength = file.length()
                    Log.d("testXX", "---------fileLength:$fileLength    filePath:${file.absolutePath}")
                    if (fileLength <= 0) {
                        hideLoading()
                        toast("加载图片失败！")
                        return
                    }
                    ActivityManagerUtil.getMemorySize()
                    if (fileLength >= ActivityManagerUtil.getMemorySize()) {
                        doCompress(file.absolutePath)
                    } else {
                        initDoodleView(ImageUtils.getBitmapFromFile(file))
                        hideLoading()
                    }
                }

                override fun onError(e: Throwable) {
                    hideLoading()
                    toast("加载图片失败：${e.message}")
                }
            }).launch()
    }


    fun clearSign() {
        mSignData.forEach { mDoodleView?.removeItem(it) }
        mSignData.clear()
    }

    fun addImage(image: String, isSign: Boolean = false) {
        Glide.with(mContext).asBitmap().load(image)
            .transform(SizeTransformation(QMUIDisplayHelper.getScreenWidth(mContext).toLong()))
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadCleared(placeholder: Drawable?) = Unit
                override fun onResourceReady(
                    resource: Bitmap, transition: Transition<in Bitmap>?,
                ) {
                    val item = mDoodleView?.createDoodleBitmap(resource)
                    if (isSign) mSignData.add(item)
                }
            })
    }

    fun addText(text: String) {
        if (FuncSwitchUtils.canUse(FuncSwitchUtils.FuncDate)) {
            mDoodleView?.createDoodleText(text)
            FuncSwitchUtils.addUseCount(FuncSwitchUtils.FuncDate)
        } else {
            showVip()
        }
    }

    fun loadSaveData() {
        if ((mDoodleView?.itemCount ?: 0) > 0) {
            mDoodleView?.save()
        } else {
            if (!this::mImageUrl.isInitialized)
                mImageUrl = arguments?.getString(Params.url) ?: ""
            mListener?.onItemSave(Pair(false, mImageUrl))
        }
    }

    fun setListener(listener: Listener): BaseFragment {
        mListener = listener
        return this
    }

    interface Listener {
        fun onItemSave(data: Pair<Boolean, String>)
    }
}